package com.dpiinc.TechPage

import android.app.Activity
import android.bluetooth.BluetoothManager
import android.content.Context
import android.os.Bundle
import android.text.TextUtils
import androidx.multidex.MultiDexApplication
import com.dpiinc.TechPage.api.RetrofitFactory
import com.dpiinc.TechPage.api.asyncSubscribe
import com.dpiinc.TechPage.pen.dialog.LowBatteryDialog
import com.dpiinc.TechPage.room.PenDaoUtils
import com.beiji.lib.pen.PenManager
import com.beiji.lib.pen.cache.SharedPreferencesHelper
import com.beiji.lib.pen.constants.PenBusTag
import com.beiji.lib.pen.constants.PenConnectState
import com.hwangjr.rxbus.RxBus
import com.hwangjr.rxbus.annotation.Subscribe
import com.hwangjr.rxbus.annotation.Tag
import com.hwangjr.rxbus.thread.EventThread
import java.util.*

/**
 * Created by X on 2018/6/17.
 */
 class AIWriteApplication : MultiDexApplication() {

    companion object {
        private const val isDebug: Boolean = false
        lateinit var instance: AIWriteApplication
        fun instance() = instance
        fun isDebug() = isDebug
    }

    override fun onCreate() {
        super.onCreate()
/*        AWLog.init(isDebug)
        PenLog.init(isDebug)
        updateLanguage()
        AIWriteSettings.init(this)
        PenScanner.instance.init(this)
        PenManager.instance.init(this)
        val blueadapter = (getSystemService(Context.BLUETOOTH_SERVICE) as BluetoothManager).adapter
       // val blueadapter = BluetoothAdapter.getDefaultAdapter()
        if (blueadapter.isEnabled && !TextUtils.isEmpty(SharedPreferencesHelper.getStringValue("key_last_connected_pen_address"))) {
            registerActivityLifecycleCallbacks(activityLifecycleCallbacks)//自动重连
        }*/
        RxBus.get().register(this)
        instance = this
    }

    fun getAiAdapter() {
        val blueAdapter = (getSystemService(Context.BLUETOOTH_SERVICE) as BluetoothManager).adapter
        if (blueAdapter != null && blueAdapter.isEnabled && !TextUtils.isEmpty(SharedPreferencesHelper.getStringValue("key_last_connected_pen_address"))) {
            registerActivityLifecycleCallbacks(activityLifecycleCallbacks)//自动重连
        }
    }

    fun getOssConfig() {
        val params = HashMap<String, String>()
        params["uId"] = UserManager.getUserId()
        params["accessToken"] = UserManager.getAccessToken()
        val request = RetrofitFactory.getInstance().getOssAuthCredentials(params)

        request.asyncSubscribe({
            AWLog.i("OssAuthCredentials", it.toString())
            if (it.StatusCode == 0) {
                val ossPath = it.OssPath
                AIWriteSettings.setOssBucket(ossPath.bucketName)
                AIWriteSettings.setOssAudioFilePrefix(ossPath.recordPath)
                AIWriteSettings.setOssDotFilePrefix(ossPath.dotPath)
                AIWriteSettings.setOssImgFilePrefix(ossPath.imagePath)
            }
        }, {
            it.printStackTrace()
        })

    }


    @Subscribe(
            thread = EventThread.MAIN_THREAD,
            tags = [(Tag(PenBusTag.CONNECT_STATE))]
    )
    @Suppress("unused")
    fun onConnectStateChanged(connectState: PenConnectState) {
        when (connectState) {
            PenConnectState.CONNECTED -> {
                toast(R.string.label_pen_status_connected)
                LowBatteryDialog.reset()
                val connectedPen = PenManager.instance.getConnectedPen() ?: return
                connectedPen.name = PenDaoUtils.getPenName(this, connectedPen.name, connectedPen.macAddress)
            }
            PenConnectState.DISCONNECTED -> {
                toast(R.string.toast_pen_disconnected)
            }
            else -> {
            }
        }
    }

    override fun onTerminate() {
        RxBus.get().unregister(this)
        super.onTerminate()
    }

    private var visibleActivityCount = 0
    var isRunningForeground = true

    private val activityLifecycleCallbacks = object : ActivityLifecycleCallbacks {
        override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) {}
        override fun onActivityPaused(activity: Activity) {}
        override fun onActivityResumed(activity: Activity) {}
        override fun onActivityDestroyed(activity: Activity) {}
        override fun onActivitySaveInstanceState(activity: Activity, outState: Bundle) {}

        override fun onActivityStarted(activity: Activity) {
            visibleActivityCount++
            if (visibleActivityCount == 1) {
                AWLog.e("running foreground.")
                isRunningForeground = true
                onRunningForeground()
            }
        }

        override fun onActivityStopped(activity: Activity) {
            visibleActivityCount--
            if (visibleActivityCount == 0) {
                AWLog.e("running background.")
                isRunningForeground = false
                onRunningBackground()
            }
        }
    }

    private fun onRunningForeground() {
        PenManager.instance.startAutoConnectTask()
    }

    private fun onRunningBackground() {
        PenManager.instance.cancelAutoConnectTask()
    }

    fun updateLanguage(){
        val app_language:String? = getSharedPreferences("app_language", Context.MODE_PRIVATE).getString("lauType", Locale.getDefault().language)
        val resources = resources
        val config = resources.configuration
        config.locale = Locale(app_language, "")
        getResources().updateConfiguration(config,resources.getDisplayMetrics())
    }

}